/**
 * Created by tanbingqin on 2019/8/22.
 */
import React from 'react'
import { connect } from 'react-redux';
import moment from 'moment'
import {messages, deepCopy, deepFullCopy, queryCurrencyPrecision, getToken} from 'share/common'
import { Row, Col, Button, Tag } from 'antd'
import 'styles/request/travel-request/travel-order-list.scss'
import trafficLineImg from 'images/request/travel/traffic_line.png'
import travelService from 'containers/request/travel-request/travel.service'
import errorMessage from 'share/errorMessage'
import config from "config";
import thirdConsumptionService from 'containers/third-consumption/third-consumption.service'

class TravelOrderList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      airPlaneUrl: '',
      hotelUrl: '',
      offlinetOrderStatus: ''
    }
  }

  componentWillMount() {}

  componentDidMount() {
    this.getZhenxuanUrl();
  }

  componentWillReceiveProps(nextProps) {
    const {orderList} = this.props;
    const {orderList: newOrderList, isOff} = nextProps;
    if (isOff && newOrderList.length) {
      this.renderOfflineTag(newOrderList);
    }
  }

  //获取天数差
  getDifferDays = (sDate, eDate) => {
    sDate = new Date(new Date(sDate).format('yyyy-MM-dd'));
    eDate = new Date(new Date(eDate).format('yyyy-MM-dd'));
    return Math.abs(Math.floor((eDate - sDate)/1000/60/60/24)) + 1
  };

  //处理火车订单类型
  processOrderType = (orderType) => {
    let orderTypeStr = '';
    switch (orderType) {
      case '1':
        orderTypeStr = messages('request.key650')/*月结机票*/;
        break;
      case '2':
        orderTypeStr = messages('request.key651')/*现付机票*/;
        break;
      case '3':
        orderTypeStr = messages('request.key652')/*月结会员酒店*/;
        break;
      case '4':
        orderTypeStr = messages('request.key653')/*月结协议酒店*/;
        break;
      case '5':
        orderTypeStr = messages('request.key654')/*现付会员酒店*/;
        break;
      case '6':
        orderTypeStr = messages('request.key655')/*现付协议酒店*/;
        break;
      case '7':
        orderTypeStr = messages('request.key656')/*月结火车票*/;
        break;
      case '8':
        orderTypeStr = messages('request.key657')/*现付火车票*/;
        break;
      case '9':
        orderTypeStr = messages('request.key658')/*月结用车*/;
        break;
      case '10':
        orderTypeStr = messages('request.key659')/*现付用车*/;
        break;
    }
    return orderTypeStr;
  };

  //处理机票退改签
  handleRefund = (order) => {
    const { itinerary } = this.props;
    let params = {
      supplierOID: itinerary.supplierOID,
      pageType: 1002,
      orderId: order.orderId,
      itineraryDirection: itinerary.itineraryDirection
    };
    let loadingKey = `${order.flightOrderOID}Loading`;
    this.setState({[loadingKey]: true});
    travelService.getRefundSSO(params).then(res => {
      this.setState({[loadingKey]: false});
      if (res.data && res.data.url) {
        window.open(res.data.url);
      }
    }).catch(err => {
      this.setState({[loadingKey]: false});
      errorMessage(err.response);
    });
  };

  //跳转甄选机票订单详情
  handleRefundZx = (approvalNum, vendorCode, isSupplierOrderNo = false) => {
    const zxUrl = this.state[`${vendorCode}Url`];
    const realmId = config.realmIds[location.host] || config.realmId;
    const { authToken: {access_token} } = this.props;
    const url = `${zxUrl}&access_token=${access_token}&pageType=orderDetail&realmId=${realmId}&customerOrderId=${approvalNum}&language=zh&&isSupplierOrderNo=${isSupplierOrderNo}&newWindowFlag=Y`;
    console.log(url)
    window.open(url);
  };

  getZhenxuanUrl = () => {
    const { user, company, isOff } = this.props;
    const {airPlaneUrl, hotelUrl} = this.state;
    isOff && (!airPlaneUrl || !hotelUrl) && thirdConsumptionService.getThirdConsumptionList(user.employeeID, company.companyOID).then(res => {
      const list = res.data;
      list.map((ven) => {
        ven.venItems.map(item => {
          const {loginUrl} = item;
          thirdConsumptionService.thirdConsumptionLogin(loginUrl).then((res) => {
            const resUrl = res.data.url;
            if (resUrl.indexOf('vendorCode=airPlane') > -1) { //甄选机票PC链接
              this.setState({
                airPlaneUrl: resUrl
              });
            } else if (resUrl.indexOf('vendorCode=hotel') > -1) { //甄选酒店PC链接
              this.setState({
                hotelUrl: resUrl
              });
            }
          });
        });
      });
    });
  };

  renderDetailTag = (approvalNum, vendorCode, isSupplierOrderNo) => {
    return <Button type="primary" size="small" className="detail-btn" onClick={() => this.handleRefundZx(approvalNum, vendorCode, isSupplierOrderNo)}>{messages('dashboard.key128')/*查看详情*/}</Button>;
  };

  renderTag = (order, type) => {
    const { itinerary } = this.props;
    let isShow = false; //是否有支持web端的单点登录地址
    if (itinerary.supplierConfig && JSON.parse(itinerary.supplierConfig) && JSON.parse(itinerary.supplierConfig)[0].webTicketRestriction) {
      isShow = true;
    }
    if (type === 'flight') {
      if (order.subOrderStatus) {
        return <Tag>{messages(`zx.flight.status${order.subOrderStatus}`)}</Tag>;
      }
      switch (order.ticketStatus) {
        case '6':
          return <Tag>{messages('request.key41')/*已退票*/}</Tag>;
          break;
        case '7':
          return <Tag>{messages('request.key42')/*已改签*/}</Tag>;
          break;
        default:
          let loadingKey = `${order.flightOrderOID}Loading`;
          return isShow ? <Button type="primary" size="small" onClick={() => this.handleRefund(order)} loading={this.state[loadingKey]}>{messages('request.key660')/*退改签*/}</Button> :
            <Tag>{messages('request.key660')/*退改签*/}</Tag>;
          break;
      }
    }
    if (type === 'hotel' || type === 'train') {
      if (type === 'hotel' && order.vendorsOrderStatus) {
        return <Tag>{messages(`zx.hotel.status${order.vendorsOrderStatus}`)}</Tag>;
      }
      switch (order.detailType) {
        case "BOOKED":
          return <Tag>{messages('request.key44')/*已订票*/}</Tag>;
          break;
        case "REFUNDED":
          return <Tag>{messages('request.key41')/*已退票*/}</Tag>;
          break;
        case "TICKETED":
          return <Tag>{messages('request.key661')/*已出票*/}</Tag>;
          break;
        case "REBOOKED":
          return <Tag>{messages('request.key42')/*已改签*/}</Tag>;
          break;
        case "CHECKOUT":
          return <Tag>{messages('request.key662')/*已离店*/}</Tag>;
          break;
        case "OTHER":
          return <Tag>{messages('common.other')/*其它*/}</Tag>;
          break;
      }
    }
    return;
  };

  renderOfflineTag = (orderList) => {
    const { supplierOrderNo, orderNo, orderId } = orderList[0] || {};
    let offlinetOrderStatus;
    this.setState({offlinetOrderStatus: ''});
    if (supplierOrderNo) { //flight
      travelService.queryFlightOrderDetail({customerOrderId: supplierOrderNo, isSupplierOrderNo: true}).then(res => {
        if (res && res.status == 200 && res.data && res.data.body) {
          const {subOrderList = [], mainOrder = {}} = res.data.body;
          const isMainOrderNo = mainOrder.customerOrderId === orderNo;
          const subOrder = isMainOrderNo ? subOrderList[0] : subOrderList.filter(item => item.subCustomerOrderId === orderNo)[0];
          offlinetOrderStatus = subOrder ? String(subOrder.subOrderStatus) : '';
          console.log('----0000----', offlinetOrderStatus)
          this.setState({offlinetOrderStatus});
        }
      });
    }
    if (orderId) { //hotel
      travelService.queryHotelOrderDetail({orderID: orderId}).then(res => {
        if (res && res.status == 200 && res.data && res.data.body) {
          offlinetOrderStatus = String(res.data.body.vendorsOrderStatus);
          console.log('----0000----', offlinetOrderStatus)
          this.setState({offlinetOrderStatus});
        }
      });
    }
  };

  render() {
    const { orderList, type, isOff, approvalType } = this.props;
    const { offlinetOrderStatus } = this.state;
    return (
      <div className="travel-order-list">
        <Row gutter={16}>
          {orderList && orderList.map(order => {
            const {subOrderStatus, vendorsOrderStatus} = order;
            const isGreyBgFlight = ['4', '5', '7', '11', '14', '15', '23', '25', '30'].indexOf(subOrderStatus || offlinetOrderStatus) > -1;
            const isGreyBgHotel = ['13', '16', '18', '19'].indexOf(vendorsOrderStatus || offlinetOrderStatus) > -1;
            return (
              <Col span={9}>
                {type === 'flight' && (
                  <div className={`ticket ${isGreyBgFlight ? 'grey-bg' : ''}`}>
                    {approvalType !== '3' && isOff && <div className="stick">{messages('mcd.offline.order')/*线下订单*/}</div>}
                    <Row>
                      <Col span={16}>
                        {!order.journeys && <span>
                          {order.iconUrl && (<img className="flight-icon" src={order.iconUrl}/>)}
                          {order.airline && <span style={{color: '#4E5B71'}}>{order.airline}&nbsp;{order.flightCode}</span>}
                        </span>}
                        {order.supplierOrderNo && <span style={{color: '#4E5B71'}}>{messages('request.key110')/*订单号*/}：{order.supplierOrderNo}</span>}
                      </Col>
                      {!order.hideTag && <Col span={8} style={{textAlign: 'right'}}>{this.renderTag(order, 'flight')}</Col>}
                      {isOff && <Col span={8} className="detail-tag">
                        {!!offlinetOrderStatus && <Row><Tag>{messages(`zx.flight.status${offlinetOrderStatus}`)}</Tag></Row>}
                        {this.renderDetailTag(order.supplierOrderNo, 'airPlane', true)}
                        </Col>}
                    </Row>
                    <Row>
                      <Col span={24}>
                        {order.failedReason && <span className="fail-reason-spn">{messages('zx.fail.reason')/*失败原因*/}：
                          {subOrderStatus === '30' ? messages('zx.flight.price.rise')/*机票已涨价*/ : (['11', '15'].indexOf(subOrderStatus) > -1 ? messages('zx.flight.meiya.fail')/*美亚系统失败:请拨打4006-139-139联系美亚客服。*/ : order.failedReason)}</span>}
                      </Col>
                    </Row>
                    {
                      order.journeys && order.journeys.length > 0 && order.journeys.map((journey, idx) => (
                        <div>
                          <div className="ticket-divider-no-circle"></div>
                          <Row>
                            <Col span={16}>
                              {order.journeys.length > 1 && <span>{messages('zx.flight.journey')/*航段*/}{idx+1}:&nbsp;</span>}
                              {journey.iconUrl && (<img className="flight-icon" src={journey.iconUrl}/>)}
                              {journey.airlineName && <span style={{color: '#4E5B71'}}>{journey.airlineName}&nbsp;{journey.flightNo}</span>}
                            </Col>
                          </Row>
                          <Row>
                            <Col span={18}>
                              {moment(journey.departureDate).format('MMM DD')}{messages('setting.key746'/*日*/)}&nbsp;
                              {moment(journey.departureDate).format('dddd')}&nbsp;
                              {journey.departureCityName}-{journey.arrivalCityName}
                            </Col>
                          </Row>
                          <Row type="flex" align="middle">
                            <Col span={8} style={{textAlign: 'left'}}>
                              <div className="font-01">{moment(journey.departureDate).format('HH:mm')}</div>
                              <div className="font-03">{journey.departureAirportName}{journey.departureTerminal || ''}</div>
                            </Col>
                            <Col span={8}>
                              <img src={trafficLineImg} style={{maxWidth: '100%'}}/>
                            </Col>
                            <Col span={8} style={{textAlign: 'right'}}>
                              <div className="font-01">{moment(journey.arrivalDate).format('HH:mm')}</div>
                              <div className="font-03">{journey.arrivalAirportName}{journey.arrivalTerminal || ''}</div>
                            </Col>
                          </Row>
                          {journey.airlineName && <Row style={{fontSize: 12}}>{journey.airlineName}{journey.flightNo}
                            {journey.planeModel && <span> | {journey.planeModel}</span>}
                            {journey.cabinClassName && <span> | {journey.cabinClassName}</span>}
                            {journey.meal && <span> | {journey.meal}</span>}
                            {journey.isMeal === 'true' && <span> | {messages('zx.has.food', {cm: '有餐食'})}</span>}
                          </Row>}
                        </div>
                      ))
                    }
                    {
                      !order.journeys && <div>
                        <Row>
                          <Col span={18}>
                            {
                              !order.isDateText && <span>
                                {moment(order.startDate || order.departureDate).format('MMM DD')}{messages('setting.key746'/*日*/)}&nbsp;
                                {moment(order.startDate || order.departureDate).format('dddd')}&nbsp;
                              </span>
                            }
                            {
                              order.isDateText && <span>{order.startDate}&nbsp;</span>
                            }
                            {order.startCity || order.departureCityName}-{order.endCity || order.arrivalCityName}
                          </Col>
                        </Row>
                        <Row type="flex" align="middle">
                          <Col span={8} style={{textAlign: 'left'}}>
                            {
                              !order.isDateText && <div className="font-01">{moment(order.startDate || order.departureDate).format('HH:mm')}</div>
                            }
                            {
                              order.isDateText && <div className="font-01">{order.startTime}</div>
                            }
                            <div className="font-03">{order.startAirport || order.departureAirportName}{order.departureTerminal || ''}</div>
                          </Col>
                          <Col span={8}>
                            <img src={trafficLineImg} style={{maxWidth: '100%'}}/>
                          </Col>
                          <Col span={8} style={{textAlign: 'right'}}>
                            {
                              !order.isDateText && <div className="font-01">{moment(order.endDate || order.arrivalDate).format('HH:mm')}</div>
                            }
                            {
                              order.isDateText && <div className="font-01">{order.endTime}</div>
                            }
                            <div className="font-03">{order.endAirport || order.arrivalAirportName}{order.arrivalTerminal || ''}</div>
                          </Col>
                        </Row>
                        {order.seatClass && <Row style={{fontSize: 12}}>{order.seatClass}</Row>}
                        {order.airlineName && <Row style={{fontSize: 12}}>{order.airlineName}{order.flightNo}
                          {order.planeModel && <span> | {order.planeModel}</span>}
                          {order.cabinClassName && <span> | {order.cabinClassName}</span>}
                        </Row>}
                      </div>
                    }
                    <div className="ticket-divider"></div>
                    {
                      (order.passenger || order.passengerName) && <Row style={{color: '#505564'}}>
                        {messages('request.key72')/*乘机人*/}：{order.passenger || order.passengerName}
                      </Row>
                    }
                    {
                      (order.amount || order.subOrderTotalAmount) && <Row className="font-02" style={{lineHeight: '20px'}}>
                        {messages('request.key663')/*合计金额*/}：CNY {this.filterMoney(order.amount || order.subOrderTotalAmount, 2)}
                        &nbsp;{messages('request.key676')/*(含税)*/}
                      </Row>
                    }
                    {order.airline && <Row className="font-04" style={{marginTop: 6}}>
                      {messages('request.key675')/*该数据由供应商提供*/}
                    </Row>}
                  </div>
                )}
                {type === 'train' && (
                  <div className="ticket" style={{background: '#E6F6F5'}}>
                    <Row style={{color: '#4E5B71'}}>
                      <Col span={16}>{messages('request.key664')/*车次*/}&nbsp;{order.trainName}</Col>
                      <Col span={8} style={{textAlign: 'right'}}>{this.renderTag(order, 'train')}</Col>
                    </Row>
                    <Row style={{color: '#1E2126'}}>
                      {moment(order.departureDateTime).format('YYYY/MM/DD HH:mm')}
                    </Row>
                    <Row type="flex" align="middle">
                      <Col span={8} style={{textAlign: 'left'}}>
                        <div className="font-01">{order.departureStationName}</div>
                        <div className="font-03">{order.departureCityName}</div>
                      </Col>
                      <Col span={8}>
                        <img src={trafficLineImg} style={{maxWidth: '100%'}}/>
                      </Col>
                      <Col span={8} style={{textAlign: 'right'}}>
                        <div className="font-01">{order.arrivalStationName}</div>
                        <div className="font-03">{order.arrivalCityName}</div>
                      </Col>
                    </Row>
                    <Row style={{fontSize: 12}}>{order.firstSeatTypeName}</Row>
                    <div className="ticket-divider"></div>
                    <Row style={{color: '#505564'}}>{messages('request.key666')/*乘坐人*/}：{order.passengerName}</Row>
                    <Row style={{color: '#505564', lineHeight: '20px'}}>{messages('request.key667')/*订单类型*/}：{this.processOrderType(order.orderType)}</Row>
                    <Row className="font-02" style={{lineHeight: '20px'}}>
                      {messages('request.key663')/*合计金额*/}：{order.currency} {this.filterMoney(order.realAmount, queryCurrencyPrecision(order.currency))}
                    </Row>
                    <Row className="font-04" style={{marginTop: 6}}>
                      {messages('request.key675')/*该数据由供应商提供*/}
                    </Row>
                  </div>
                )}
                {type === 'hotel' && (
                  <div className={`ticket ${isGreyBgHotel ? 'grey-bg' : ''}`} style={{background: `${isGreyBgHotel ? '#f7f7f7' : '#E2F3FA'}` }}>
                    {isOff && <div className="stick">{messages('mcd.offline.order')/*线下订单*/}</div>}
                    <Row style={{color: '#4E5B71'}}>
                      <Col span={16}>{messages('request.key110')/*订单号*/}：{order.tmcOrderID || order.orderId}</Col>
                      {!order.hideTag && <Col span={8} style={{textAlign: 'right'}}>{this.renderTag(order, 'hotel')}</Col>}
                      {isOff && <Col span={8} className="detail-tag">
                        {!!offlinetOrderStatus && <Row><Tag>{messages(`zx.hotel.status${offlinetOrderStatus}`)}</Tag></Row>}
                        {this.renderDetailTag(order.orderId, 'hotel')}
                        </Col>}
                    </Row>
                    {false && <Row>
                      <div className="standard-exceed-sub">{order.beyondStandardReason}</div>
                    </Row>}
                    {isOff && <div className="ticket-divider-no-circle"></div>}
                    <Row>
                      {moment(order.startTime).format('MMM DD')}{messages('setting.key746'/*日*/)}
                      {messages('request.key668')/*入住*/}&nbsp;&nbsp;&nbsp;
                      {moment(order.endTime).format('MMM DD')}{messages('setting.key746'/*日*/)}
                      {messages('request.key669')/*离店*/}
                    </Row>
                    <Row className="font-01">{order.hotelName}</Row>
                    <Row style={{fontSize: 12}}>
                      {order.roomCount}{messages('request.key347')/*间*/}
                      {messages('request.key468', {arg1: this.getDifferDays(order.startTime, order.endTime) - 1}/*{arg1}晚*/)}
                      {order.roomTypeName && <span> | {order.roomTypeName}</span>}
                      {order.breakfast && <span> | {order.breakfast}</span>}
                    </Row>
                    <div className="ticket-divider"></div>
                    <Row style={{color: '#505564'}}>{messages('request.key670')/*入住人*/}：{order.clientNames}</Row>
                    {order.payType && <Row style={{color: '#505564', lineHeight: '20px'}}>
                      {messages('request.key671')/*公司账户付款类型*/}：{order.payType === 'X' ? messages('request.key672')/*现付*/ : messages('request.key673')/*主账户支付*/}
                    </Row>}
                    <Row className="font-02" style={{lineHeight: '20px'}}>
                      {messages('request.key663')/*合计金额*/}：{order.currency} {this.filterMoney(order.totalAmount, queryCurrencyPrecision(order.currency))}
                    </Row>
                    {!order.vendorsOrderStatus && <Row className="font-04" style={{marginTop: 6}}>
                      {messages('request.key675')/*该数据由供应商提供*/}
                    </Row>}
                  </div>
                )}
              </Col>
            )
          })}
        </Row>
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    company: state.login.company,
    user: state.login.user,
    authToken: state.main.authToken
  }
}

TravelOrderList.propTypes = {
  orderList: React.PropTypes.array,
  type: React.PropTypes.string,
  itinerary: React.PropTypes.object
};

TravelOrderList.defaultProps = {
  orderList: [],
  type: '',
  itinerary: {}
};

export default connect(mapStateToProps)(TravelOrderList)
